package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.dto.WarehouseReceiptQueryDTO;
import com.intelligent.mapper.WarehouseReceiptMapper;
import com.intelligent.pojo.WarehouseReceipt;
import com.intelligent.service.WarehouseReceiptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入库单服务实现
 */
@Service
public class WarehouseReceiptServiceImpl extends ServiceImpl<WarehouseReceiptMapper, WarehouseReceipt>
    implements WarehouseReceiptService {

    @Override
    public IPage<WarehouseReceipt> pageList(WarehouseReceiptQueryDTO query) {
        // 设置分页参数
        Page<WarehouseReceipt> page = new Page<>(query.getPageNum() != null ? query.getPageNum() : 1, query.getPageSize() != null ? query.getPageSize() : 5);

        // 创建查询条件
        LambdaQueryWrapper<WarehouseReceipt> wrapper = new LambdaQueryWrapper<>();

        if (query.getReceiptNo() != null && !query.getReceiptNo().isEmpty()) {
            wrapper.like(WarehouseReceipt::getReceiptNo, query.getReceiptNo());
        }
        if (query.getReceiptType() != null ) {
            wrapper.like(WarehouseReceipt::getReceiptType, query.getReceiptType());
        }

        // 使用 MyBatis-Plus 内置分页查询
        return this.page(page, wrapper);
    }


    @Override
    public WarehouseReceipt getDetailById(Long id) {
        return getById(id);
    }

    @Autowired
    private WarehouseReceiptMapper warehouseReceiptMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(WarehouseReceipt receipt) {
        // 1. 生成入库单号: RK + 年月日 + 4位随机数
        String receiptNo = "RK" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
            + String.format("%04d", (int)(Math.random() * 10000));
        receipt.setReceiptNo(receiptNo);

        if (receipt.getReceiptTime() == null) {
            receipt.setReceiptTime(new java.util.Date());
        }

        return warehouseReceiptMapper.add(receipt);
    }
}
